// test_jsoncpp.cpp
#include <json/json.h>
#include <iostream>
#include <sstream>

int json_cpp_demo(void) {
    std::cout << "=== jsoncpp 测试程序开始 ===" << std::endl;

    // 1. 创建 JSON 对象并写入数据
    Json::Value root;
    root["name"] = "Alice";
    root["age"] = 30;
    root["city"] = "Beijing";
    root["is_student"] = false;

    // 添加数组
    Json::Value hobbies;
    hobbies.append("reading");
    hobbies.append("coding");
    hobbies.append("hiking");
    root["hobbies"] = hobbies;

    // 输出格式化 JSON
    Json::StreamWriterBuilder builder;
    builder["indentation"] = "  "; // 两个空格缩进
    std::string json_str = Json::writeString(builder, root);
    std::cout << "\n【序列化后的 JSON】:\n" << json_str << std::endl;

    // 2. 从字符串解析 JSON
    std::string input_json = R"({
        "product": "Embedded Device",
        "version": "1.0",
        "features": ["wifi", "bluetooth", "gps"],
        "price": 99.99
    })";

    Json::CharReaderBuilder parse_builder;
    Json::Value parsed_root;
    std::string errs;

    std::istringstream iss(input_json);
    if (Json::parseFromStream(parse_builder, iss, &parsed_root, &errs)) {
        std::cout << "\n【解析成功】:" << std::endl;
        std::cout << "产品: " << parsed_root["product"].asString() << std::endl;
        std::cout << "版本: " << parsed_root["version"].asString() << std::endl;
        std::cout << "价格: " << parsed_root["price"].asDouble() << std::endl;

        std::cout << "功能: ";
        const Json::Value& features = parsed_root["features"];
        for (const auto& feature : features) {
            std::cout << feature.asString() << " ";
        }
        std::cout << std::endl;
    } else {
        std::cout << "解析失败: " << errs << std::endl;
        return 1;
    }

    std::cout << "\n=== jsoncpp 测试程序结束 ===" << std::endl;
    return 0;
}
